package com.tx.admin.core.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.mapping.Map;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.tx.admin.util.common.ReflectionUtils;
import com.tx.admin.util.common.UUIDUtils;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@MappedSuperclass
@Data
public  class SuperEntity extends BaseRowModel implements Serializable{

	@Id
	@ApiModelProperty("编号")
	@ExcelProperty(value = "编号")
	private String id;
	

	@Temporal(TemporalType.TIMESTAMP)
	@ApiModelProperty("更新时间")
	@ExcelProperty(value = "更新时间" )
	private Date uptTime;
	
	@Temporal(TemporalType.TIMESTAMP)
	@ApiModelProperty("创建时间")
	@ExcelProperty(value = "创建时间")
    private Date crtTime;

	@ApiModelProperty("数据标记")
	private String dataFlag;


	@Override
	public boolean equals(Object obj) {
		
		if(obj instanceof SuperEntity) {

			SuperEntity other = (SuperEntity) obj;
			if (id == null) {
				return false;
			} else if (id.equals(other.id)) {
				return true;
			}else {
				return true;
			}
	
		}

		return super.equals(obj);
	}

	@Override
	public int hashCode() {
		return id.hashCode();
	}
	
	public void init() {
		if(StringUtils.isBlank(id)) {
			this.id = UUIDUtils.getId(this.getClass());
		}
		if(this.crtTime == null) {
			this.crtTime = new Date();
		}
		this.uptTime = new Date();
		//对所有值字段初始化
		ReflectionUtils.getAllDeclaredFields(getClass())
		.forEach(val -> {
			
			Object value = ReflectionUtils.invokeGetter(this, val.getName());
			if(value != null) {
				return;
			}
			Class clazz = val.getType();
			if(Integer.class.isAssignableFrom(clazz)) {
				value=0;
			}else if(Double.class.isAssignableFrom(clazz)) {
				value=0.0;
			}else if(Boolean.class.isAssignableFrom(clazz)) {
				value= false;
			}else if(Date.class.isAssignableFrom(clazz)) {
				value= new Date();
			}else if(String.class.isAssignableFrom(clazz)) {
				value="0";
			}else if(List.class.isAssignableFrom(clazz)){
				value = new LinkedList<>();
			}else if(Map.class.isAssignableFrom(clazz)) {
				value = new HashMap<>();
			}
			ReflectionUtils.invokeSetter(this, val.getName(), value);
		});;
	}
	
	
}
